package com.zxh.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxh.util.Constant;
import com.zxh.util.HttpPoolUtil;
import org.apache.log4j.Logger;

/**
 * Created by zhangxh on 2016/7/8.
 */
public class BaiduUtil {
    private static Logger logger=Logger.getLogger(BaiduUtil.class);
    private static String TOKEN=null;
    private static long EXPIRES_IN=0;
    public static void init(){
        refreshToken();
//        Timer timer=new Timer();
//        TimerTask task=new TimerTask() {
//            @Override
//            public void run() {
//                try {
//                    refreshToken();
//                    logger.info("当前获取的tok为："+TOKEN);
//                } catch (Exception e) {
//                    logger.error("获取token失败", e);
//                }
//            }
//        };
//        timer.schedule(task, (EXPIRES_IN-100)*1000);
    }
    public static void refreshToken(){
        String getTokenURL = "http://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" +
                "&client_id=" + Constant.getPropertity("apiKey") + "&client_secret=" + Constant.getPropertity("secretKey") ;
        JSONObject json= JSON.parseObject(HttpPoolUtil.postRetStr(getTokenURL));
        EXPIRES_IN=json.getLong("expires_in");//过期时间
        TOKEN=json.getString("access_token");
    }
    public static String getToken(){
        return TOKEN;
    }
}
